//
//  OAuthViewController.swift
//  JKDWeiBoExercise
//
//  Created by 简康达 on 16/5/14.
//  Copyright © 2016年 JKD. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {
    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        loadWebView()
        webView.delegate = self
        
    }

}
//布局导航栏按钮
extension OAuthViewController{
   private func setupNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style:.Plain, target: self, action: #selector(OAuthViewController.close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: #selector(OAuthViewController.autoFill))
        title = "登录界面"
    }
    //加载webview
   private func loadWebView() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        guard let url = NSURL(string: urlString) else{
            return
        }
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
}

//方法的监控
extension OAuthViewController{
   @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
   @objc private func autoFill() {
        let jsCode = "document.getElementById('userId').value='13724054064';document.getElementById('passwd').value='JKD84284523';"
    webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
}
extension OAuthViewController : UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    // 加载某一个页面时会执行该方法
    // 返回值 : true : 继续加载该页面 false : 不会加载该页面
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlString = request.URL?.absoluteString else{
            return true
        }
        if urlString.containsString("code=") {
          let codeString = urlString.componentsSeparatedByString("code=").last
//            用code换取aceessToken
            UserAccountViewModel.shareIntance.loadAccessToken(codeString!)
            self.dismissViewControllerAnimated(true, completion: {
                
            })
            return false
        }
        return true
    }
    
}
